package conf

import (
	"ManageServer/utils/logger"
	"fmt"
	"github.com/Unknwon/goconfig"
	"os"
	"path/filepath"
	"runtime"
)

var goos, exepath, exedir, runpath string
var ENV, DirPath, ConfPath, LogPath string
var ConfFile *goconfig.ConfigFile

func GetEnv() {
	// 输出环境日志
	goos = runtime.GOOS
	exepath, _ = filepath.Abs(os.Args[0])
	exedir, _ = filepath.Abs(filepath.Dir(os.Args[0]))
	runpath, _ = os.Getwd()

	fmt.Println("操作系统：", goos)
	fmt.Println("执行程序路径：", exepath)
	fmt.Println("执行程序文件路径：", exedir)
	fmt.Println("运行目录路径：", runpath)
}

func CheckConf(env string) (err error) {
	var filename string
	if env == "prod" {
		filename = "conf.ini"
	}
	if env == "test" {
		filename = "conf-test.ini"
		ENV = "test"
	}

	// 查找配置文件位置，顺便设置文件夹路径
	ConfPath = exedir + "/" + filename
	DirPath = exedir
	defer func() {
		if err != nil {
			fmt.Println("未读取到配置文件：", err.Error())
		} else {
			fmt.Println("配置文件：", ConfPath)
		}
	}()

	_, err = os.Stat(ConfPath) //os.Stat获取文件信息
	if err == nil {
		// 查询到配置文件则结束
		return
	}
	// 否则查看运行路径
	ConfPath = runpath + "/" + filename
	DirPath = runpath
	_, err = os.Stat(ConfPath) //os.Stat获取文件信息

	return
}

func GetConf() (err error) {
	//加载配置文件
	ConfFile, err = goconfig.LoadConfigFile(ConfPath)
	return
}

func InitLog() (err error) {
	LogPath, err = ConfFile.GetValue("log", "path")
	if err != nil {
		fmt.Println("未找到日志路径", err.Error())
		return
	}
	err = logger.CreateLog(LogPath)
	if err != nil {
		fmt.Println("启动日志模块失败！", err.Error())
		return
	}
	fmt.Println("日志将打印在：", LogPath)
	// 初始化日志,通过：logger.ErrorLogger.Error("") 打印日志
	logger.InitLogger("panic")
	logger.InitLogger("info")
	logger.InitLogger("error")
	return
}
